const axios = require("axios");

class Init {
  template = {};
  async setup(options) {
    if (typeof options.template === "string") {
      const template = await this.checkTemplate(options.template);
      if (template) {
        this.template = template;
      }
    }
    await this.selectTemplate(this.template);
  }

  async checkTemplate(url) {
    try {
      const res = await axios.get(url);
      return res.data;
    } catch (error) {
      console.log(error);
    }
  }

  async selectTemplate(template) {
    /**
     * template: {
     *    host: "http://github.com/xxx.git",
     *    remote: "http://github.com/xxx2.git",
     * }
     */
    // inquirer 是一个用于在 Node.js 命令行程序中 与用户进行交互式输入 的模块，例如：多选、单选、输入
    const inquirer = (await require("inquirer")).default;
    const answers = await inquirer.prompt([
      {
        type: "input",
        name: "name",
        message: "请输入项目名",
        default: "my-project",
      },
      {
        type: "list",
        name: "template",
        message: "请选择模板",
        choices: Object.keys(template),
      },
    ]);
    // { name: 'my-project', template: 'remote' }
    // console.log(answers);
    const gitRepo = template[answers.template];
    await this.downloadRepo(gitRepo, answers.name)
  }

  async downloadRepo(url, name) {
    // 下载动画
    const { createSpinner } = require('nanospinner')
    const spinner = createSpinner()
    // 下载git仓库工具
    const git = require('git-promise')
    const fs = require('fs-extra')

    // 开始
    spinner.start({ text: '正在下载模板...' })
    await git(`clone ${url} ./${name}`)
    // 结束
    spinner.success({ text: `下载模板成功 🚀🚀🚀 \n🌍 cd ${name} \n🌍 npm install \n🌍 npm run dev` })
  }
}

module.exports = new Init();
